// 部门管理模块

const router = require("koa-router")();
const Leave = require("../models/leaveSchema");
const Dept = require("../models/deptSchema");
const util = require("../utils/util");
router.prefix("/leave");
//申请列表
router.get("/list", async (ctx) => {
    const { applyState, type } = ctx.request.query;
    const { page, skipIndex } = util.pager(ctx.request.query);
    const authorization = ctx.request.headers.authorization;
    const { data } = util.decoded(authorization);
    try {
        let params = {};
        if (type == "approve") {
            // 负责人审核
            if (applyState == 1 || applyState == 2) {
                // 申请单子为待审批状态
                params.curAuditUserName = data.userName;
                params.$or = [{ applyState: 1 }, { applyState: 2 }];
            } else if (applyState > 2) {
                // 审批中，审批拒绝，审批通过。需要审批流中有当前审批人
                params = { "auditFlows.userId": data.userId, applyState };
            } else {
                // 查询全部,当前审批人需要审批的单子
                params = { "auditFlows.userId": data.userId };
            }
        } else {
            // 申请休假的用户
            params = {
                "applyUser.userId": data.userId,
            };
            if (applyState) params.applyState = applyState;
        }
        const query = Leave.find(params);
        const list = await query.skip(skipIndex).limit(page.pageSize);
        const total = await Leave.countDocuments(params);
        ctx.body = util.success({
            page: {
                ...page,
                total,
            },
            list,
        });
    } catch (error) {
        ctx.body = util.fail("查询失败" + error.stack);
    }
});

// 休假申请
router.post("/operate", async (ctx) => {
    const { _id, action, ...params } = ctx.request.body;
    const authorization = ctx.request.headers.authorization;
    const { data } = util.decoded(authorization);
    try {
        if (action === "create") {
            // 生成申请单号 XJ20220505
            const orderNo = "XJ" + util.formatDate(new Date(), "yyyyMMdd");
            const total = await Leave.countDocuments();
            params.orderNo = orderNo + total;

            // 获取用户当前部门id
            const id = data.deptId.pop();
            // 查找负责人信息
            const dept = await Dept.findById(id);
            // 获取人事部门和财务部门负责人信息
            const userList = await Dept.find({ deptName: { $in: ["人事部门", "财务部门"] } });

            // 完整审批人：当前所在部门的负责人->人事->财务
            let auditUsers = dept.userName;
            // 当前审批人
            const curAuditUserName = dept.userName;
            // 审批流
            // 审批流：用户提交->当前所在部门的负责人->人事->财务
            const auditFlows = [
                {
                    userId: dept.userId,
                    userName: dept.userName,
                    userEmail: dept.userEmail,
                },
            ];
            userList.forEach((item) => {
                console.log(item.userName);
                auditFlows.push({
                    userId: item.userId,
                    userName: item.userName,
                    userEmail: item.userEmail,
                });
                auditUsers += "," + item.userName;
            });

            params.auditUsers = auditUsers;
            params.curAuditUserName = curAuditUserName;
            params.auditFlows = auditFlows;
            params.auditLogs = [];
            params.applyUser = {
                userId: data.userId,
                userName: data.userName,
                userEmail: data.userEmail,
            };

            const res = await Leave.create(params);
            ctx.body = util.success("", "创建成功");
        } else {
            // 作废
            const res = await Leave.findByIdAndUpdate(_id, { applyState: 5 });
            ctx.body = util.success("", "操作成功");
        }
    } catch (error) {
        ctx.body = util.fail("操作失败" + error);
    }
});

// 审核。1：待审批，2：审批中，3：审批拒绝，4：审批通过，5：作废
router.post("/approve", async (ctx) => {
    const { action, remark, _id } = ctx.request.body;
    const authorization = ctx.request.headers.authorization;
    const { data } = util.decoded(authorization);
    let params = {};
    try {
        const doc = await Leave.findById(_id);
        let auditLogs = doc.auditLogs || [];
        if (action == "refuse") {
            // 审核拒绝，只把状态值改变
            params.applyState = 3;
        } else {
            // 审核通过情况
            if (doc.auditFlows.length == doc.auditLogs.length) {
                // 审批流和日志相匹配，流程结束。
                ctx.body = util.success("当前申请单已处理，请勿重复提交");
                return;
            } else if (doc.auditFlows.length == doc.auditLogs.length + 1) {
                // 优先处理最后一级
                params.applyState = 4;
            } else if (doc.auditFlows.length > doc.auditLogs.length) {
                // 审核中
                params.applyState = 2;
                // 把下一个审核人，改成当前审核人
                params.curAuditUserName = doc.auditFlows[doc.auditLogs.length + 1].userName;
            }
        }
        // 增加审核日志，不管成功失败
        auditLogs.push({
            userId: data.userId,
            userName: data.userName,
            createTime: new Date(),
            remark,
            action: action == "refuse" ? "审核拒绝" : "审核通过",
        });
        params.auditLogs = auditLogs;
        const res = await Leave.findByIdAndUpdate(_id, params);
        ctx.body = util.success("", "操作成功");
    } catch (error) {
        ctx.body = util.fail("查询失败" + error);
    }
});

// 右上角通知接口
router.get("/count", async (ctx) => {
    const authorization = ctx.request.headers.authorization;
    const { data } = util.decoded(authorization);
    try {
        let params = {};
        params.curAuditUserName = data.userName;
        params.$or = [{ applyState: 1 }, { applyState: 2 }];
        const total = await Leave.countDocuments(params);
        ctx.body = util.success(total);
    } catch (error) {
        ctx.body = util.fail("查询失败" + error);
    }
});
module.exports = router;
